package cn.tedu.circle.admin.account.handler;


import cn.tedu.circle.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult handleServiceException(cn.tedu.tmall.common.ex.ServiceException serviceException){
        return JsonResult.fail(serviceException);
    }

    @ExceptionHandler
    public JsonResult handleBindException(BindException e) {
        // List<FieldError> fieldErrors = e.getFieldErrors();
        String defaultMessage = e.getFieldError().getDefaultMessage();
        return JsonResult.fail(cn.tedu.tmall.common.enumerator.ServiceCode.ERROR_BAD_REQUEST, defaultMessage);
    }

    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e){
        /*提示管理员异常跟踪信息----一般禁止使用*/
//        e.printStackTrace();
        log.warn("程序运行过程中出现未知异常:",e);
        String message = "服务器忙,请稍后再试";
        return JsonResult.fail(cn.tedu.tmall.common.enumerator.ServiceCode.ERROR_UNKNOWN,message);
    }

    @ExceptionHandler
    public JsonResult handle(ConstraintViolationException e){
        String message = null;
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
             message = constraintViolation.getMessage();
        }
        return JsonResult.fail(cn.tedu.tmall.common.enumerator.ServiceCode.ERROR_BAD_REQUEST,message );
    }
}
